import { Base64 } from 'js-base64'
import cryptoJs from 'crypto-js'


// base64字符串加密
export const base64Encode = (val: string) => {
    return Base64.encode(val)
}

// base64字符串解密密
export const base64Decode = (val: string) => {
    return Base64.decode(val)
}

/* 
*  cryptoJs 
*/
const key = cryptoJs.enc.Utf8.parse('BkPyAbTqBCDsEBGz')
// const iv = cryptoJs.enc.Utf8.parse()

// cryptoJs加密
export const cpjsEncode = () => {
    // const srcs = cryptoJs.enc.Utf8.parse(str)
    // const encrypted = cryptoJs.AES.encrypt(srcs, key, {
    //     iv: iv,
    //     mode: cryptoJs.mode.ECB,
    //     padding: cryptoJs.pad.Pkcs7,
    // })
    // return cryptoJs.enc.Base64.stringify(encrypted.ciphertext)
}

// cryptoJs解密
export const cpjsDecode = (str: string) => {
    const iv = cryptoJs.enc.Utf8.parse(str.substring(0, 16))
    const decrypted = cryptoJs.AES.decrypt(str.substring(16), key, {
        iv: iv,
        mode: cryptoJs.mode.CBC,
        padding: cryptoJs.pad.ZeroPadding
    });
    return decrypted.toString(cryptoJs.enc.Utf8)
}
/**
 * @Description 节流函数
 * @param { Function } fn 需要做节流的函数
 * @param { Function } intervalTime 间隔实践
 * @param { Function } immediate 是否立即执行
 * @return { Number } intervalTime
 **/
  export const throttle = <T extends (...args: any[]) => void>(
    fn: T,
    intervalTime: number = 200,
    immediate: boolean = true
  ): T => {
    let oldTime = Date.now();
    let timer: ReturnType<typeof setTimeout> | null = null;
  
    const throttledFunction = function (this: any, ...args: Parameters<T>) {
      const nowTime = Date.now();
      const context = this;
  
      const later = () => {
        oldTime = Date.now();
        fn.apply(context, args);
      };
  
      const remaining = intervalTime - (nowTime - oldTime);
  
      if (remaining <= 0) {
        if (timer) {
          clearTimeout(timer);
          timer = null;
        }
        oldTime = nowTime;
        fn.apply(context, args);
      } else if (!timer && immediate) {
        timer = setTimeout(later, remaining);
      }
    } as T;
  
    return throttledFunction;
  };
/* 
*  cryptoJs  end
*/

/* 
*  视频观看进度
*/
export function getVideoDuration(file: File): Promise<number> {
  return new Promise((resolve, reject) => {
    const url = URL.createObjectURL(file);
    const video = document.createElement('video');
    video.preload = 'metadata';

    video.onloadedmetadata = () => {
      URL.revokeObjectURL(url);   // 及时释放内存
      resolve(video.duration);    // 单位：秒
    };
    video.onerror = reject;
    video.src = url;
    console.log(url)
  });
}
export default {}